﻿using System.Collections;
using System.Web;
using AhoraSiMvc3.Models;

namespace AhoraSiMvc3.DataAccess
{
    /// <summary>
    /// Unit Of Work Factory implementation that uses HttpContext to store the UoW instance.
    /// </summary>
    public class HttpContextUnitOfWorkFactory : IUnitOfWorkFactory
    {
        #region Constants

        /// <summary>
        /// Key used tos store UoW in HttpContext.
        /// </summary>
        private const string CurrentUnitOfWorkKey = "CurrentUnitOfWorkKey";

        #endregion

        #region IUnitOfWorkFactory

        /// <summary>
        /// Returns the current UoW instance. If non exists, creates one.
        /// </summary>
        /// <remarks>Uses HttpContext to store the current UoW.</remarks>
        public IUnitOfWork Current
        {
            get
            {
                IUnitOfWork uow = null;
                if (HttpContext.Current.Items.Contains(CurrentUnitOfWorkKey))
                {
                    uow = HttpContext.Current.Items[CurrentUnitOfWorkKey] as IUnitOfWork;
                }
                if (uow == null)
                {
                    uow = new UnitOfWork();
                    HttpContext.Current.Items[CurrentUnitOfWorkKey] = uow;
                }
                return uow;
            }
        }

        /// <summary>
        /// Dispose the current UoW, if any.
        /// </summary>
        /// <returns>UoW disposed</returns>
        public IUnitOfWork DisposeUnitOfWork()
        {
            IDictionary contextItems = HttpContext.Current.Items;
            IUnitOfWork uow = null;
            if (contextItems.Contains(CurrentUnitOfWorkKey))
            {
                uow = contextItems[CurrentUnitOfWorkKey] as IUnitOfWork;
                if (uow != null)
                    uow.Dispose();
                contextItems.Remove(CurrentUnitOfWorkKey);
            }
            return uow;
        }

        #endregion
    }

}